<?php

namespace yak\layui;

use yii\helpers\Html;
use yii\i18n\Formatter;

/**
 * Class YakFormatter
 * @package yak
 */
class YakFormatter extends Formatter
{
    public function asSelected($key, $params)
    {
        if ($key === null) {
            return $this->nullDisplay;
        }

        $cls = $key;
        if (!is_numeric($cls)) {
            $cls = ord($key);
        }

        $class = ['layui-bg-orange', 'layui-bg-green', 'layui-bg-cyan', 'layui-bg-blue', 'layui-bg-black', 'layui-bg-gray'];
        return !isset($params[$key]) ? $this->nullDisplay : Html::tag('i', $params[$key], [
            'class' => 'layui-badge ' . $class[$cls % 6]
        ]);
    }

    public function asLayuiIcon($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        return Html::tag('span', '', ['class' => "layui-icon {$value}"]);
    }

    public function asIcon($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        return Html::tag('span', '', ['class' => "fa {$value}"]);
    }

    public function asThumb($value)
    {
        if (empty($value)) {
            return $this->nullDisplay;
        }
        return Html::img($value, [
            'width' => 30, 'data-src' => $value, 'yak-event' => 'pop-thumb', 'data-label' => '图片'
        ]);
    }

    public function asDehtml($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        return html_entity_decode($value);
    }

    public function asDecodeUnicode($value)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
            create_function(
                '$matches',
                'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
            ),
            $value);
    }

}